# @Time : 2020/12/24 17:00
# @Author : Fioman 
# @Phone : 13149920693
import socket
from xml.dom.minidom import parse,Document
import time


# 获取通信标识符
def get_transaction_id():
    now_second = time.time()
    last_three = str(now_second).split('.')[1][:3]
    now = time.strftime("%Y%m%d%H%M%S", time.localtime(now_second))
    transaction_id = now + last_three
    return transaction_id

def write_recv_message(messageRecv):
    with open("./message_recv.xml", "wb") as f:
        f.write(messageRecv[1:-1])  # 去除前两个字节.一个是char(2),一个是char(3)

# 解析接收到的消息
def parse_recv_msg(msgRecv):
    if msgRecv == "MESSAGE_ERROR":
        return None, None
    write_recv_message(msgRecv)
    dom = parse(r"./message_recv.xml")
    rootNode = dom.documentElement
    msgNameNode = rootNode.getElementsByTagName("messagename")[0]
    bodyDict = {}
    bodyNode = rootNode.getElementsByTagName("body")[0]
    for node in bodyNode.childNodes:
        if node.nodeName != "#text":
            bodyDict[node.nodeName] = node.childNodes[0].data
    retNode = rootNode.getElementsByTagName("returncode")[0]
    msgName = msgNameNode.childNodes[0].data
    retCode = retNode.childNodes[0].data
    return msgName,bodyDict,retCode




def send_msg_to_device(self, msgName, data):
    """
    向eap发送消息,注意发送消息的时候,要加上消息头和消息结尾
    :param data: xml消息的字节二进制格式
    :return:
    """
    msgSend = bytes(chr(2), encoding="ascii") + data + bytes(chr(3), encoding="ascii")
    print("发送消息到EAP: {}".format(msgName))  # 这里最好是解析出来消息的类型.也就是发送消息的名称,内容都解析出来.
    try:
        self.sock.sendall(msgSend)
    except Exception as e:
        print("in send_msg_to_eap(),self.sock.sendall() 出现异常: {}".format(str(e)))
        self.js.logger.debug("in send_msg_to_eap(),self.sock.sendall() 出现异常: {}".format(str(e)))
        return False
    return True

if __name__ == '__main__':
    HOST = "127.0.0.1"
    PORT =  5000
    BUFSIZE = 1024
    ADDR = (HOST,PORT)
    tcpServerSock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    tcpServerSock.bind(ADDR)
    tcpServerSock.listen(5)

    while True:
        print("等待客户端的连接........")
        tcpClientSock,addr = tcpServerSock.accept()
        print("{} 连接上来了".format(addr))
        while True:
            try:
                data = tcpClientSock.recv(BUFSIZE)
                if not data:
                    continue
                msgName,bodyDict,retCode = parse_recv_msg(data)
                print("接收到消息名称:{}".format(msgName))
                with open(r'./ask_msg.xml', 'rb') as f:
                        data = f.read()
                msgSend = bytes(chr(2), encoding="ascii") + data + bytes(chr(3), encoding="ascii")
                tcpClientSock.send(msgSend)
                print("发送了回复消息")
            except Exception as e:
                print(str(e))
                break

        tcpClientSock.close()
    tcpServerSock.close() # 关闭服务器socket